package com.forgenet.testclient.panel;


import com.forgenet.message.PacketId;
import com.forgenet.message.base.req.ReqGateLoginPacket;
import com.forgenet.testclient.ClientMain;
import com.sparrow.common.util.HttpUtil;
import com.sparrow.common.util.JsonUtil;
import com.sparrow.common.util.PropertiesUtil;
import com.sparrow.socket.http.bean.HttpResponse;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

/**
 * 登录界面（账号+密码）
 */
public class LoginPanel extends JPanel implements ActionListener {

    private final JTextField usernameField;
    private final JButton loginButton;
    private final JButton createBtn;

    public LoginPanel() {
        setLayout(new GridBagLayout());

        int row = 0;

        JLabel usernameLabel = new JLabel("账号:");
        add(usernameLabel, createGBC(0, row));
        usernameField = new JTextField(20);
        add(usernameField, createGBC(1, row++));

        JLabel passwordLabel = new JLabel("密码:");
        add(passwordLabel, createGBC(0, row));

        loginButton = new JButton("登录");
        loginButton.addActionListener(this);
        add(loginButton, createGBC(1, row++));

        createBtn = new JButton("创建角色");
        createBtn.addActionListener(e -> ClientMain.showPanel(CreateRolePanel.class));
        add(createBtn, createGBC(1, row)); // 放在下一行
    }


    private GridBagConstraints createGBC(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        return gbc;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String userName = usernameField.getText().trim();
        if (userName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "账号不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            String url = PropertiesUtil.getProperty("login.url");
            int packetId = PacketId.LoginServer.REQ_ACCOUNT_AUTH;
            url = String.format(url + "?packetId=%d&userName=%s&password=%s", packetId, userName, "");
            HttpUtil.getAsync(url, null, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String jsonString = response.body().string();
                        HttpResponse httpResponse = JsonUtil.parse(jsonString, HttpResponse.class);
                        int code = httpResponse.getCode();
                        if (code == 0) {
                            JOptionPane.showMessageDialog(LoginPanel.this, "账号不存在", "账号不存在", JOptionPane.ERROR_MESSAGE);
                        } else if (code == 1) {
                            handleRespLogin(httpResponse);
                        }
                    }
                }
            });
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    private void handleRespLogin(HttpResponse httpResponse) {
        System.out.println("登录服验证成功 " + JsonUtil.toJSON(httpResponse));
        String gateIp = (String) httpResponse.getResults().get("gate-ip");
        Integer gatePort = (Integer) httpResponse.getResults().get("gate-port");
        String token = (String) httpResponse.getResults().get("token");
        ClientMain.connect("gate", gateIp, gatePort);
        //登录网关
        ReqGateLoginPacket reqGateLoginPacket = new ReqGateLoginPacket();
        reqGateLoginPacket.setToken(token);
        ClientMain.channel.writeAndFlush(reqGateLoginPacket);
    }

    private void showNextPanel() {
        JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(this);
        frame.getContentPane().remove(this);
        LoginGamePanel gamePanel = new LoginGamePanel(); // 或 GamePanel
        frame.getContentPane().add(gamePanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        gamePanel.requestFocus();
    }
}
